<?php
/**
 * Created by PhpStorm.
 * User: gby
 * Date: 2018/7/03
 * Time: 13:49
 */

namespace Lm\Controllers;

use \Admin\Frontend\Controllers\ControllerBase;
use Admin\Models\hrm\XhhrmDepart;
use Admin\Models\overt\XhovertAreainfo;
use Helpers\Assets;
use Helpers\Hrm;
use Helpers\Main;
use Helpers\Template;
use Helpers\Tool;
use Helpers\User;
use Admin\Models\lm\XHLmHousing;
use Modules\Power;

//重构 by qgz 20181229
class HousingController extends ControllerBase
{
    /**
     * 检查类型
     * @param $type
     * @param string $operate
     * @return bool
     * create by gby 20180705
     */
    public function checkPower($type, $operate = '')
    {
        if ($type == 1) {
            $tag = 'Lm_HousingHouse';
        } else {
            return false;//不存在标签类型
        }
        if ($operate != '') {
            $tag .= '_' . ucfirst($operate); //首字母大写
        }
        return Power::exist($tag);
    }

    /**
     * 错误信息
     * @param bool $isView
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     * create by gby 20180705
     */
    public function sendPowerMsg($isView = false)
    {
        if ($isView) {
            return $this->sendViewError('没有权限');
        } else {
            return $this->sendErrorResponse(400, '缺少权限');
        }
    }

    /**
     * 住房列表
     *
     * create by gby 20180705
     */
    public function houseListAction()
    {
        if (!Power::exist('Lm_HousingHouse')) {
            return $this->sendViewError('您没有权限查看此页面');
        }
        $this->view->pick('housing/houseList');
        Main::showNavPosition();
        Assets::easyUI();
        Assets::importJs('js/housing/houseList.js');
        Assets::sweetAlert2();
        $listButton = $listSearchArr = [];
        $secArea = Hrm::getDepArray('XHYYB', 1, true);
        $secArea = ['' => '--运营区--'] + array_column($secArea, 'text', 'id');

        if (Power::exist('Lm_HousingHouse_Add')) {
            $listButton[] = ['plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus'];
        }
        if (Power::exist('Lm_HousingHouse_Del')) {
            $listButton[] = ['plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash'];
        }
        $listSearchArr[] = ['type' => 'select', 'id' => 'select_secArea', 'data' => $secArea, 'default' => ''];
        $listSearchArr[] = ['type' => 'select', 'id' => 'select_thirdArea', 'data' => ['' => '--运营县--'],
                            'default' => ''];
        $province = ['' => '--选择省--'] + array_column(array_values($this->getAreaByLevel(1)), 'areaName', 'areaCode');
        $listSearchArr[] = ['type' => 'select', 'id' => 'select_province', 'data' => $province, 'default' => ''];
        $listSearchArr[] = ['type' => 'select', 'id' => 'select_city', 'data' => ['' => '--选择市--'], 'default' => ''];
        $listSearchArr[] = ['type' => 'select', 'id' => 'select_county', 'data' => ['' => '--选择区--'], 'default' => ''];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： '];
        $listSearchArr[] = ['type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search',
                            'style' => 'margin-left:10px'];
        return $this->view->setVars([
            'List' => Template::createList('list', 'housingList', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButton),
            ]),
            'Form' => true,
        ]);
    }

    /**
     * 根据父id获取子部门
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by gby 20180705
     */
    public function findAreaAction($id)
    {
        $thirdDeps = XhhrmDepart::getDeps($id);
        $arr[] = ['id' => '', 'text' => '请选择'];
        foreach ($thirdDeps as $index => $row) {
            $arr[] = ['id' => $index, 'text' => $row];
        }
        return $this->sendJsonResponse($arr);
    }

    /**
     * 获取数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by gby 20180705
     */
    public function getHouseAction()
    {
        if (!$this->checkPower(1)) {
            return $this->sendPowerMsg();
        }
        $key = $this->request->getPost('key', 'string');
        $province = $this->request->getPost('province', 'string');
        $city = $this->request->getPost('city', 'string');
        $county = $this->request->getPost('county', 'string');
        $secArea = $this->request->getPost('secArea', 'string');
        $thirdArea = $this->request->getPost('thirdArea', 'string');
        try {
            $builder = $this->modelsManager->createBuilder()
                ->from('Admin\\Models\\lm\\XHLmHousing')
                ->columns('*')
                ->where('bDelete = 0 ');
            if ($key) {
                $builder->andWhere('sOperator like :key:', ['key' => '%' . $key . '%']);
            }
            if ($province && strpos($province, '选择') === false) {
                $builder->andWhere('sProvince = :province:', ['province' => $province]);
            }
            if ($city && strpos($city, '选择') === false) {
                $builder->andWhere('sCity = :city:', ['city' => $city]);
            }
            if ($county && strpos($county, '选择') === false) {
                $builder->andWhere('sCounty = :county:', ['county' => $county]);
            }
            if ($secArea && strpos($secArea, '选择') === false) {
                $builder->andWhere('iSecArea = :secArea:', ['secArea' => $secArea]);
            }
            if ($thirdArea && strpos($thirdArea, '选择') === false && strpos($thirdArea, '运营') === false) {
                $builder->andWhere('iThirdArea = :thirdArea:', ['thirdArea' => $thirdArea]);
            }
            $data = Main::runBuilderPage(
                $builder,
                ['iType' => [0 => '', 1 => '家', 2 => '学校'], 'iSecArea' => [0 => ''], 'iThirdArea' => [0 => '']]
            );
            Main::runUserNameById($data['rows'], ['iCreateUserId' => 'iCreateUserId'], true);
            $deps = XhhrmDepart::getDepEnum();
            Tool::runEnum($data['rows'], [
                'iSecArea' => $deps,
                'iThirdArea' => $deps
            ]);
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 新增表单
     *
     * create by gby 20180705
     */
    public function addFormAction()
    {
        if (!Power::exist('Lm_HousingHouse_Add')) {
            return $this->sendViewError('您没有权限查看此页面');
        }
        $this->view->pick('housing/addHouseForm');
        Assets::select2();
        Assets::importJs('js/housing/addHouse.js');
        return $this->view->setVars([
            'province' => $this->getAreaByLevel(1),
            'secArea' => array_column(Hrm::getDepArray('XHYYB', 1, true), 'text', 'id'),
        ]);
    }

    /**
     * 保存信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by gby 20180705
     */
    public function saveInfoAction()
    {
        $data = $this->request->getPost();
        $data['sProvince'] = strpos($data['sProvince'], '选择') !== false ? '' : $data['sProvince'];
        $data['sCity'] = strpos($data['sCity'], '选择') !== false ? '' : $data['sCity'];
        $data['sCounty'] = strpos($data['sCounty'], '选择') !== false ? '' : $data['sCounty'];
        try {
            if (!isset($data['iRHId'])) {
                if (!$this->checkPower(1, 'add')) {
                    return $this->sendPowerMsg();
                }
                $obj = new XHLmHousing();
            } else {
                if (!$this->checkPower(1, 'edit')) {
                    return $this->sendPowerMsg();
                }
                $obj = XHLmHousing::findFirst($data['iRHId']);
            }
            $obj->assign($data);
            // 判断要存入的数据是否全部为空
            $a = array_filter($data);
            if (count($a) > 0) {
                if (!$obj->save()) {
                    return $this->sendErrorResponse(500, '保存失败');
                }
                return $this->sendSuccessResponse('保存成功');
            } else {
                return $this->sendErrorResponse(400, '请填写信息再提交');
            }
        } catch (\Exception $e) {
            return $this->sendErrorResponse(400, $e->getMessage());
        }
    }

    /**
     * 删除
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     * create by gby 20180705
     */
    public function delHouseAction()
    {
        $id = $this->request->getPost('id');
        if (!$id) {
            return $this->sendErrorResponse(200, '请选择要删除的项');
        }
        if (!$this->checkPower(1)) {
            return $this->sendPowerMsg(false);
        }
        $house = XHLmHousing::findFirst($id);
        if (!User::isAdmin() && $house->iCreateUserId != User::getId()) {
            return $this->sendErrorResponse(401, '没有权限');
        }
        $house->bDelete = 1;
        if (!$house->save()) {
            return $this->sendErrorResponse(500, '删除失败');
        }
        return $this->sendSuccessResponse('删除成功');
    }

    /**
     * houseTab
     *
     * @param $iRHId
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|\Phalcon\Mvc\View|string
     *
     * create by gby 20180705
     */
    public function houseTabAction($iRHId)
    {
        if (!$this->checkPower(1)) {
            return $this->sendPowerMsg(true);
        }
        $staff['市场部'] = Hrm::getDepStaffByTag('XHSCB');
        $staff['运营部'] = Hrm::getDepStaffByTag('XHYYB');
        $info = XHLmHousing::findFirst($iRHId);
        if (!$info) {
            return $this->sendViewError('未找到数据');
        }
        $this->view->pick('housing/houseTab');
        Assets::select2();
        Assets::importJs('js/housing/houseTab.js');
        return $this->view->setVars([
            'province' => json_encode($this->getAreaByLevel(1)),
            'city' => json_encode($this->getAreaByLevel(2)),
            'county' => json_encode($this->getAreaByLevel(3)),
            'info' => json_encode($info->toArray()),
            'staff' => $staff,
            'iRHId' => $iRHId,
            'power' => $this->checkPower(1, 'edit'),
            'secArea' => array_column(Hrm::getDepArray('XHYYB', 1, true), 'text', 'id'),
        ]);
    }


    /**
     * 获取地区等级
     *
     * @param $level
     * @return array
     *
     * create by gby 20180705
     */
    public function getAreaByLevel($level)
    {
        $area = XhovertAreainfo::find([
            'conditions' => ' areaLevel = :level:',
            'bind' => ['level' => $level]
        ])->toArray();
        $area = array_column($area, null, 'areaCode');
        return $area;
    }
}
